const app = getApp();

Page({
  data: {
    responsibilityOptions:  getApp().globalData.enums.responsibilityOptions,
    couponOptions: getApp().globalData.enums.couponOptions,
    couponStatusTexts: getApp().globalData.enums.couponStatusTexts,
    responsibilityLabel: "", // 初始化
    stats: {
      totalCount: 0,
      avgDuration: 0,
      resolveRate: 0,
      unresolvedCount: 0
    },
    latestRecord: null
  },

  getResponsibilityLabel(value) {
    const options = this.data.responsibilityOptions;
    return (options.find(item => item.value === value) || {}).label || '未知';
  },

  onShow() {
    this.loadData();
  },
  
  loadData() {
    const records = app.getAllRecords();
    
    // 计算统计数据
    const totalCount = records.length;
    const resolvedCount = records.filter(r => r.status === 'resolved').length;
    const unresolvedCount = records.filter(r => r.status === 'unresolved').length;
    const totalDuration = records.reduce((sum, r) => sum + parseInt(r.duration), 0);
    
    const stats = {
      totalCount,
      avgDuration: totalCount ? Math.round(totalDuration / totalCount) : 0,
      resolveRate: totalCount ? Math.round((resolvedCount / totalCount) * 100) : 0,
      unresolvedCount
    };
    
    // 获取最新记录
    const rawRecord = records.length ? records[0] : null;
    const latestRecord = rawRecord ? {
      ...this.formatRecord(rawRecord),
      couponIcon: this.data.couponOptions.find(opt => opt.value === rawRecord.couponType)?.icon || '/images/coupon.png',
      couponName: this.data.couponOptions.find(opt => opt.value === rawRecord.couponType)?.label || '其他补偿'
    } : null;
    
    this.setData({ 
      responsibilityLabel: this.getResponsibilityLabel(latestRecord?.responsibility),
      stats,
      latestRecord });
  },
  
  // 格式化记录数据用于显示
  formatRecord(record) {
    const category = record.tags ? record.tags.join(' · ') : record.category;
    const dateObj = new Date(record.date);
    const date = `${dateObj.getFullYear()}年${dateObj.getMonth() + 1}月${dateObj.getDate()}日`;
    const time = `${dateObj.getHours().toString().padStart(2, '0')}:${dateObj.getMinutes().toString().padStart(2, '0')}`;
    
    // 冲突等级标签
    const conflictLabels = ['轻微', '低', '中等', '高', '严重'];
    const conflictLabel = conflictLabels[record.conflictLevel - 1] || '中等';
    
    // 状态文本
    const statusTexts = {
      resolved: '已解决',
      unresolved: '未解决',
      'in-progress': '进行中'
    };

    const couponStatusTexts = {
      used: '已使用',
      unused: '未使用',
      expired: '已过期'
    }

    // 1. 获取当前时间（兼容小程序环境）
    const currentTime = new Date().getTime();
    
    // 2. 解析过期时间（假设 couponExpiry 是时间戳或格式化的日期字符串）
    let expiryTime;
    if (typeof record.couponExpiry === 'string') {
      // 如果是日期字符串（如 "2023-12-31"），转为时间戳
      expiryTime = new Date(record.couponExpiry).getTime();
    } else if (typeof record.couponExpiry === 'number') {
      // 如果是时间戳（如 1704038400000），直接使用
      expiryTime = record.couponExpiry;
    } else {
      console.error('Invalid couponExpiry format:', record.couponExpiry);
    }

    // 3. 检查是否过期
    if (currentTime > expiryTime) {
      record.couponStatus = 'expired'
    }
    
    return {
      ...record,
      date,
      time,
      conflictLabel,
      statusText: statusTexts[record.status] || '已解决',
      couponStatusTexts: couponStatusTexts[record.couponStatus] || '已过期',
      couponType: record.couponType || ''
    };
  },
  
  // 导航到新增记录页
  navigateToAddRecord() {
    wx.navigateTo({
      url: '/pages/add-record/add-record'
    });
  },
  
  // 导航到详情页
  navigateToDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/record-detail/record-detail?id=${id}`
    });
  }
});